<template>
  <div>
    <!-- 新增弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog">
      
      <el-form ref="addform" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入学科内容"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="subjectName">
          <!-- active-value switch 打开时的文字描述 active-colorswitch 打开时的背景色 inactive-value switch 关闭时的文字描述 inactive-color	switch 关闭时的背景色-->
          <el-switch 
            v-model="form.isFrontDisplay" 
            :active-value="1" 
            :inactive-value="0" 
            active-color="#13ce66" 
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addSubject, detailSubject, updateSubject} from '@/api/subjects'
export default {
  name: 'AddDialog',
  props: {
    dialogVisible:{
      default: false,
      type: Boolean,
    },
    dialogTitle:{
      type: String
    }
  },
  data() {
    return {
      form: {
        subjectName: '',
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.$emit('close-dialog')
      // 清空表单 和校验信息
      this.form = {
        subjectName: '',
        isFrontDisplay: 1
      },
      this.$refs.addform.resetFields();
    },
    confirm() {
      // 兜底校验
      this.$refs.addform.validate(async(valid) => {
        if(valid) {
          // 校验通过
          // 判断新增还是编辑
          if(this.form.id) {
            // console.log('更新',this.form.id);
            // 修改
            await updateSubject(this.form)
            // 提示用户
            // this.$message.success('更新成功')
          }else{
            // 调新增接口
            await addSubject(this.form)
            // 提示用户
            // this.$message.success('新增成功')
          }
          
          this.$message.success(`${this.form.id? '更新成功':'新增成功'}`)
          // 关闭弹窗
          this.closeDialog()
          // 刷新列表
          this.$emit('get-list')
        }
      })
    },
    // 数据回填
    async getDetail(id) {
      // console.log('11',id);
      // 点击编辑数据回调
      const res = await detailSubject(id)
      // console.log(res);
      this.form = res
      console.log(this.form.id);
    }
  },
}
</script>

<style>

</style>